package edu.caece.langprocessor;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Runner {

	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				"classpath:/main-context.xml");

		String fileName = "";
		String outputFileName = "";
		String formattedFileName = "";
		
		if (args.length != 0 && args.length >= 1) {
			fileName = args[0];
			if (args.length >= 2)
				outputFileName = args[1];
			if (args.length >= 3)
				formattedFileName = args[2];

			
			Processor p = (Processor) appContext.getBean("processor");
			Reader r;
			Writer w;
			try {
				r = new FileReader(fileName);

				p.proccess(r);

				r.close();

				if (formattedFileName.length() > 0){
					w = new FileWriter(outputFileName);
					w.write(p.getGeneratedCode());
					w.close();
				}
				
				if (formattedFileName.length() > 0){
					w = new FileWriter(formattedFileName);
					w.write(p.getFormattedCode());
					w.close();
				}


			} catch (FileNotFoundException e) {
				e.printStackTrace();
				System.exit(1);
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(2);
			}

		} else {
			System.out
					.println("Usage: java -jar lpse input-filename outputASM-filename sourceFormatted-filename");
		}
	}

}
